import * as request from '../constant/fetch-request'
import HTTP_CODE from '../constant/http-code'
import {message} from 'antd'

export const getOrganizations = (page = 1) => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/organizations/pageable?page=${--page}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch({
          type: 'REFRESH_ORGANIZATION_PAGE',
          data: res.body
        })
      }
    })()
  }
}
export const getOrganization = organizationId => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/organizations/${organizationId}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch({
          type: 'REFRESH_ORGANIZATION',
          data: res.body
        })
      }
    })()
  }
}
export const addOrganization = (organization, callback) => {
  return () => {
    (async () => {
      const res = await request.post(`./api/organizations`, organization)
      if (res.status === HTTP_CODE.CREATED) {
        callback()
      }
    })()
  }
}

export const editOrganization = (organization, callback) => {
  return () => {
    (async () => {
      const res = await request.update(`./api/organizations/${organization.id}`, organization)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        callback()
      }
    })()
  }
}

export const getOrganizationUsers = (organizationId) => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/organizations/${organizationId}/users`)
      if (res.status === HTTP_CODE.OK) {
        dispatch({
          type: 'REFRESH_ORGANIZATION_USERS',
          data: res.body
        })
      }
    })()
  }
}

export const removeAdminRole = (organizationId, userId) => {
  return dispatch => {
    (async () => {
      const res = await request.del(`./api/organizations/${organizationId}/users/${userId}/roles`)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        message.success('移除成功')
        dispatch(getOrganizationUsers(organizationId))
      }
    })()
  }
}

export const addOrganizationAdminRole = (organizationId, userId) => {
  return dispatch => {
    (async () => {
      const res = await request.update(`./api/organizations/users/roles`, {organizationId, userId})
      if (res.status === HTTP_CODE.NO_CONTENT) {
        message.success('添加成功')
        dispatch(getOrganizationUsers(organizationId))
      }
    })()
  }
}
